<?php
/**
 * This is the model class for table "{{user}}".
 *
 * The followings are the available columns in table '{{user}}':
 * @property integer $ID
 * @property string $email
 * @property string $password
 */
class User extends CActiveRecord
{
	public $rememberMe=false;
	public $passwordConfirm;
	public $verifyCode;
	public $roles;
	public $name;	

	public $newPassword = '';
	public $newPasswordConfirm = '';
	
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{user}}';
	}
	
	public function scopes()
	{
		return array(
			'customers' => array(
				'with'=>'authAssignment',
				'condition' => 'authAssignment.itemname = "customer"'
			),
			'managers' => array(
				'with'=>'authAssignment',
				'condition' => 'authAssignment.itemname = "manager"'
			),
			'developers' => array(
				'with'=>'authAssignment',
				'condition' => 'authAssignment.itemname = "developer"'
			)
		);
	}

	/**
	 * Описываем правила валидации модели
	 */
	public function rules()
	{
		return array(
			// Common
			array('email', 'email'),
			array('password, email, last_name, first_name', 'length', 'max'=>50),
			array('password, email, last_name, first_name', 'length', 'min'=>4),
            array('roles', 'default'),

			// Login
			array('email, password', 'required', 'on'=>'login'),
			array('password', 'authenticate', 'on'=>'login'),
			array('rememberMe', 'boolean', 'on'=>'login'),
			
			// Api login
			array('email, password', 'required', 'on'=>'token'),
			array('password', 'token', 'on'=>'token'),
			
			// Register
			array('email, password, passwordConfirm, verifyCode, first_name, last_name', 'required', 'on'=>'register'),
			array('email', 'emailExists', 'on'=>'register'),
			array('password', 'isSamePasswords', 'on'=>'register', 'compare'=>'passwordConfirm'),
			array('verifyCode', 'captcha', 'on'=>'register'),
			
			// Create/Update
			array('email, password, passwordConfirm, first_name, last_name', 'required', 'on'=>'insert'),
			array('email, first_name, last_name', 'required', 'on'=>'update'),
			array('email', 'emailExists', 'on'=>'insert'),
			array('password', 'isSamePasswords', 'on'=>'insert', 'compare'=>'passwordConfirm'),
			array('newPasswordConfirm', 'safe', 'on'=>'update'),
			array('newPassword', 'isSamePasswords', 'on'=>'update', 'compare'=>'newPasswordConfirm'),

			// Search
			array('ID, email, first_name, last_name', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * Описание связей между моделями
	 */
	public function relations()
	{
		return array(
			'authAssignment' => array(self::HAS_MANY, 'AuthAssignment', 'userid')
		);
	}

	/**
	 * Подписи полей
	 */
	public function attributeLabels()
	{
		return array(
			'ID' => 'ID',
			'login' => 'Логин',
			'first_name' => 'Имя',
			'last_name' => 'Фамилия',
			'password' => 'Пароль',
			'passwordConfirm' => 'Повтор пароля',
			'email' => 'E-mail',
			'verifyCode' => 'Код проверки',
			'newPassword' => 'Новый пароль',
			'newPasswordConfirm' => 'Подтверждение нового пароля',
			'rememberMe' => 'Запомнить меня',
			'roles' => 'Роли'
		);
	}

	/**
	 * Поиск
	 */
	public function search()
	{
		$criteria=new CDbCriteria;

        $criteria->compare('email',$this->email,true);
        $criteria->compare('password',$this->password,true);
        $criteria->compare('first_name',$this->password,true);
        $criteria->compare('last_name',$this->password,true);
        
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	/**
	 * Аутентификация пользователя
	 */
	public function authenticate($attribute, $params)
    {
        $identity = new UserIdentity($this->email, $this->password);
        if(!$identity->authenticate())
		{
            $this->addError('password', 'Неправильное имя пользователя или пароль.');
		}
		else
		{
			if($this->rememberMe)
			{
				Yii::app()->user->login($identity, 3600*24*7);
			}
			else
			{
				Yii::app()->user->login($identity);
			}
		}
    }
	
	public function token($attribute, $params)
    {
        $identity = new UserIdentity($this->email, $this->password);
		$this->token = $identity->authenticate($token = true);
    }
	
	public function setToken()
	{
		$this->token = crypt(time());
		$expireDate = new DateTime();
		$expireDate->add(new DateInterval('P30D'));
		$this->tokenExpired = $expireDate->format('Y-m-d H:i:s');
	}
	
	/**
	 * Проверка подтверждения пароля
	 */
	public function isSamePasswords($attribute, $params)
    {
		$compare = $params['compare'];
		
		if(!isset($this->$attribute) || !isset($this->$compare) || $this->$attribute != $this->$compare)
		{
            $this->addError('password', 'Пароли не совпадают');
		}
    }
	
	/**
	 * Проверка существования пользователя с указанным e-mail
	 */
	public function emailExists($attribute, $params)
	{
		$result = User::model()->findByAttributes(array('email' => $this->email));
		if($result !== null)
		{
			$this->addError('email', 'Пользователь с таким e-mail уже существует');
		}
	}
	
	public function getName()
	{
		return $this->name;
	}

	protected function beforeSave()
    {
        if(!parent::beforeSave())
            return false;

		// Если новая запись
        if($this->isNewRecord)
        {
			// Криптуем парль
            $this->password = crypt($this->password, $this->password);
        }
        elseif($this->scenario=='update')
        {
            if(!empty($this->newPassword))
            {
                $this->password = crypt($this->newPassword, $this->newPassword);
            }
        }
        return true;
    }
    
    protected function afterSave()
    {
		// Присваиваем роль пользователю
		if(!empty($this->roles))
		{
			$auth = Yii::app()->authManager;
			foreach($auth->getRoles() as $name => $val)
			{
				$auth->revoke($name, $this->id);
			}
			foreach($this->roles as $role)
			{
				$auth->assign($role, $this->id);
			}
		}
        return true;
	}
	
	protected function beforeDelete()
    {
        if(!parent::beforeDelete())
            return false;
		// Перед удалением пользователя
		// удаляем информацию о его роли
        $auth = Yii::app()->authManager;
        $authItems = $auth->getAuthItems(null, $this->id);
        foreach($authItems as $authItem){
            $authItem->revoke($this->id);
        }
        return true;
    }
	
	protected function afterFind()
	{
		$this->name = $this->first_name . ' ' . $this->last_name;
		return parent::afterFind();
	}
}
